Repository navigation
feat(chat): Draw a reply's Markdown instead of its source - #705
Conversation
|
CI failure diagnosed and fixed in
Root cause. The hook repo pins Why Fix: pin Verified against a cold environment rather than my warm cache, since the warm one was what hid this: PRE_COMMIT_HOME=<fresh dir> pre-commit run pretty-format-toml --all-files
# [INFO] Installing environment for .../language-formatters-pre-commit-hooks.
# Pretty format TOML.......................................................Passed
# installed: toml_sort-0.24.4
# git status --porcelain -- src-tauri/Cargo.toml -> (empty)154 node tests still pass. — Claude Code agent, on @omesser's behalf. |
Third approach to #677: parse in the webview, with a vendored library. GFM, because that is the flavour harnesses emit. Tokens to DOM nodes, so the reply never reaches markup. The caret is moved with append, never insertBefore. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The webview cannot do this itself: there is no opener plugin and nothing intercepts navigation, so an <a href> would take the chat window to the page and the conversation with it. The scheme gate sits at the last edge before the OS so no caller routes around it, and it parses rather than prefix-matches, because a link target is model output. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
7ef756d to
f7221a6
Compare
The &OsStr change missed a #[cfg(not(unix))] call site, which no local build can see. Type-checked this time by extracting the arm into a scratch crate for x86_64-pc-windows-msvc, since ring's build script cannot compile whole-crate without MSVC headers. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
|
Windows CI failure fixed in What broke. Generalising the per-platform opener from Audited rather than patched one-by-one. Every call site of both changed functions, How it is verified now. And confirmed that check is not vacuous, by reintroducing exactly the bug CI caught: It reproduces CI's failure locally and passes when fixed.
Still true and worth keeping in view: the Windows arm is type-checked, not run. Nothing here executes — Claude Code agent, on @omesser's behalf. |
A reviewer approves on the diff, and the diff is the one thing that cannot show them a rendered list. Checked in rather than attached: the gh CLI cannot upload, and a link to a branch dies on the squash merge. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Why
A reply was drawn as its source text, so Markdown a model emits reached the user as punctuation:
**bold**showed the asterisks, a bulleted list stayed a run of hyphens, fenced code had no code styling. Harnesses emit Markdown by default and cannot be asked not to, so almost every substantial reply read worse than the model wrote it.This lands after #702, which stopped
parse_proposalflattening a reply's line breaks. That fix was a prerequisite: Markdown is newline-significant, and a renderer handed a space-joined line cannot recover lists, paragraphs or fences. The two compose — #702 makes the structure survive, this draws it.What it looks like
The same Harness reply, both ways, at the real 420-point column width: on the
left what the user sees today, on the right what this branch draws. Bold, inline
code, a bulleted list, a fenced block with its language, and a link.
Rendered by this branch's own
src/markdown.jsandsrc/chat-ui.css— theproduction renderer and the production stylesheet, on the real
.row.them/.said.mdstructurechat.jsbuilds. Captured in headless Chrome, not inthe app's WKWebView, so it proves the renderer and the CSS rather than the
embedding; the caret and the live click are not in it. Checked into the
repository and linked by commit SHA per
docs/agents/writing.md— theghCLI cannot attach an image, and a branch link dies on the squash merge.
What changed, and why it is in the webview
Markdown formatting is drawing, not state. It is derived deterministically from the reply text and carries no authority. This repo states that split in four places —
src/main.js:1("The webview draws the Characters and owns none of their state"),src/chat.js:8,src-tauri/src/main.rs:411, and most preciselyCONTEXT.md:288: "Engine names the Cue on the frame; the webview draws and synthesizes it." The Cue is the same shape: the Engine makes the semantic decision, the webview turns it into pixels.Two other approaches were built and rejected. A hand-rolled JS parser owned 216 lines of CommonMark logic we would have to keep correct — and it shipped a
DOMExceptionin the streaming path plus***bold-italic***rendering with stray asterisks. A Rustpulldown-cmarkparse shipping tokens over IPC put a presentation concern behind a serialization boundary, so every future view decision — syntax highlighting, collapsible fences, a per-block copy button — would become a cross-language change plus a new serde variant on both sides. The full comparison, with numbers, is on #677.src/vendor/marked.esm.js—marked@18.0.13, 78 lines / 44,963 bytes, zero imports, zero runtime dependencies. Vendored becausetauri.conf.jsonis"frontendDist": "../src"with CSPdefault-src 'self': no build step, no bundler, and a CDN import is blocked. Provenance, reproduce command and sha256 are insrc/vendor/README.md, and a test asserts the hash so an in-place edit fails loudly.src/markdown.js— 244 lines that contain no parsing. It is a token-to-DOM switch overmarked's AST, building elements withcreateElementandtextContent.Why
marked, and why GFMSelected on fidelity to what Harnesses actually emit, since this is a Harness client. The evidence says GFM, not bare CommonMark: Codex ships its prompt in the open and emits pipe tables anyway (
openai/codex#22015); Claude Code has its own table, task-list and strikethrough issues; the ACP adapter generates Markdown, growing a code fence until it is longer than anything inside it, so 4+ backtick fences arrive on the wire; Zed, the reference ACP client, renders agent chunks withENABLE_TABLES | ENABLE_STRIKETHROUGH | ENABLE_TASKLISTSplus a linkify pass; and VS Code vendorsmarkedverbatim and renders chat through its token API (markedInstance.lexer()), with a dedicated file for wrapping agent tables in a scroll container — the same architecture, arrived at independently.Rejected:
markdown-it(self-contained ESM is minified-only at 138 KB, 2 of 4 GFM features by default, flat open/close tokens rather than a tree),commonmark.js(real AST but no tables, strikethrough, task lists or autolinks — exactly what agents emit),micromark/mdast(need a bundler),snarkdown(HTML string, no AST),markdown-wasm(needswasm-unsafe-eval).Security
No HTML string is ever produced.
marked's HTML writer is not used; the token API feedscreateElement+textContent, which makes injection structurally impossible rather than sanitized after the fact. A reply is untrusted — model output, steerable by an MCP server's content.Links open in the user's browser. A link renders as
<span class="md-link" data-href>— deliberately not an<a href>, because there is noshelloropenerplugin intauri.conf.jsonand nothing intercepts navigation, so anhrefwould take the chat window itself to the page and the conversation with it.default-src 'self'does not stop a top-level navigation, and neithertarget="_blank"norwindow.openreaches the system browser from a webview. Only the native side can hand a URL to the OS.So: one delegated
clicklistener on the log invokes a newopen_linkcommand, which callsplatform::open_url.The scheme gate is in Rust, at the last edge before the OS, so no caller can route around it —
src/markdown.jsfilters too, and neither check trusts the other. It is decided by parsing with theurlcrate (already a dependency) rather than by matching a prefix, which is what makesJaVaScRiPt:,javascript:,java<tab>script:and a leading newline all resolve to the scheme they really are and get refused.http,httpsandmailtopass; a refused scheme returns an error rather than silently doing nothing, so a dead link can be told from a turned-away one.Two details that are easy to get wrong and are worth a reviewer's eye:
open_urlis a sibling ofopen_path, not a widening of it.open_pathcallsensure_filefirst, so a URL handed to it would be created on disk as a file named after the URL. The two share the per-platform opener below them, which is the only part that actually differs." https://example.com "opens ashttps://example.com/.The per-platform opener is now
&OsStrrather than&Pathso both entry points share it. All three arms already accept a URL: macOSopen, Linuxxdg-open, WindowsShellExecuteW.Commandexecs directly with no shell, so there is no metacharacter to quote, and a parsed URL always starts with its scheme so it can never be read as an option flag.How to verify
node --test tests/ cargo test --workspace cargo clippy --workspace --all-targets -- -D warnings181 node tests pass, 448 Rust tests pass, clippy clean.
grep -n 'innerHTML\|insertAdjacentHTML\|outerHTML\|document.write' src/*.jsreturns nothing — and that is now asserted by a test, sweepingsrc/andsrc/vendor/forinnerHTML,eval(andnew Function. It was true by construction before and nothing enforced it.14 adversarial payloads, run rather than reasoned:
<script>alert(1)</script>,<img src=x onerror=alert(1)>,<iframe src=javascript:alert(1)>,[x](javascript:alert(1)),[x](data:text/html,…),JaVaScRiPt:,javascript:,\njavascript:,java\tscript:,vbscript:, an unterminated fence, and a malformed table. Two tests assert over all of them: no element outside a 26-tag allowlist is ever built, and no node carries anhrefordata-hrefthat is nothttps?:ormailto:.Streaming.
drawSaidreads the caret, removes it, rebuilds, re-appends — noinsertBeforeanywhere, so theNotFoundErrorthat broke the hand-rolled branch cannot occur; there is no reference node to be wrong about. Tests stream four chunks, one landing mid-marker, asserting after each that the caret is still in the row, is the same node, and appears once. The DOM stand-in'sinsertBeforeasserts its reference node is a child — the permissive version is what hid that bug.The scheme gate was mutation-tested. Disabling the allowlist (
if false) failsa_link_that_runs_or_reads_does_not_openandan_obfuscated_scheme_is_still_that_scheme; restored from a scratch copy, nevergit checkout, with the tree clean after. Four gate tests cover the three allowed schemes, the four that run or read (javascript,data,vbscript,file), seven obfuscated spellings ofjavascript:, and the parsed-not-original property.11 mutations run. Nine killed. Two survived and were real findings, not test gaps: a
caret?.remove()thatreplaceChildrenalready made redundant (deleted), and an unreachable branch ininline()(deleted). A third survived until a test was added for formatting inside a list item — a case the suite genuinely lacked.Notes
img-src 'self' data:, so a model-supplied remote image cannot load and fetching one would be a beacon), raw HTML inline and block (this is the security property, not a gap), footnotes, HTML entities (markedleaves them in token text for its HTML writer; decoding would mean owning a 2000-name table), and syntax highlighting (the info string sets alanguage-*class that nothing reads yet).markedhas published no readable ESM since v16 — 15.0.12 is 2189 readable lines; 16.4.1 through 18.0.13 are 72–78 minified. Taking the readable one means pinning 15.x and giving up three majors. Standing in for reading it: a pinned version, a registry-matching sha256 asserted by a test, npm SLSA provenance, and theeval/new Functionsweep above.overflow-xat the chat width, link styling, the caret inside the last paragraph — is visually unverified. True of all three candidate branches.codespellactually bites today (it flags minifier identifiers), but a fixer silently rewriting a hash-pinned third-party parser is corruption;.b64files carry the same exclusion for the same reason.Closes #677
— Claude Code agent, on @omesser's behalf.
🤖 Generated with Claude Code